<template>
  <div class="aaa">
    <el-upload  class="upload-demo"  drag
      :on-change="onFileChange" accept="image/*"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <div style="display: flex;align-items: center;justify-content: space-around;">
      <img v-if="imgurl" :src="imgurl" alt="Uploaded Image" @load="extractColor" />
      <el-icon><i-bi-arrow-right /></el-icon>
      <div v-if="colors.length">
        <div v-for="(color, index) in colors" :key="index"
             :style="`height: 100px;width: 100px;background-color: ${color};`"
        ></div>
      </div>
      <el-icon><i-bi-arrow-right /></el-icon>
      <div :style="`height: 100px;width: 100px;background-color: ${mainColors};`"></div>
    </div>
    <div>
      <el-input v-model="timespase" /> <el-button @click="covertime">转换</el-button>
      {{timestr}}
    </div>
    <div>
      <el-input v-model="publicUrl" width="500px"></el-input>
      <el-image :src="publicUrl" style="max-width: 10vw"></el-image>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import ColorExtractor from "@/tools/ColorExtractor";

let imgurl = ref<string | null>(null);
let colors = ref<string[]>([]);
let mainColors = ref<string>();
let timespase = ref('223149');
let timestr = ref('');
let publicUrl = ref('https://img-home.csdnimg.cn/images/20240218021830.png');

const onFileChange = (file:any) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const target = e.target;
    if (target && typeof target.result === 'string') {
      imgurl.value = target.result; // 直接赋值
    } else {
      console.error('读取文件时 target 为空或结果不是字符串');
    }
  };
  reader.readAsDataURL(file.raw); // 将文件读取为 DataURL
};

const extractColor = async () => {
  if (!imgurl.value) return;
  colors.value.length = 0;
  mainColors.value = undefined;
  // 提取三个主色调
  const dominantColors = await ColorExtractor.getDominantColors(imgurl.value, 3);
  // 将提取到的颜色格式化为 rgb 形式
  for (let i = 0; i < dominantColors.length; i++) {
    const rgbColor = `rgb(${dominantColors[i][0]}, ${dominantColors[i][1]}, ${dominantColors[i][2]})`;
    if (isNearWhite(dominantColors[i])) {
      console.log(`主颜色 ${rgbColor} 接近 白色.`);
    } else if (mainColors.value == undefined) {
      mainColors.value = rgbColor;
    }
    colors.value.push(rgbColor);
  }
};
//判断是否趋近白色
const isNearWhite = (color: number[]): boolean => {
  const threshold = 180;  // 设置阈值 ，越趋近255 越白
  return color[0] > threshold && color[1] > threshold && color[2] > threshold;
};

function covertime() {
  const totalSeconds = Number(timespase.value.slice(0, -3));
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  timestr.value = `${minutes}分${seconds}秒`;
}
</script>

<style scoped lang="scss">
.aaa img {
  width: 200px;
  height: 200px;
}
</style>
